const fs = require('fs');
const readline = require('readline');


const lineToObject = (line) => {

	// console.log(splitResult);
	return line.match(/(\S+)/g);
	// fs.appendFileSync('result.txt', JSON.stringify(splitResult));
};

const readAreas = () => {
    const testFile = 'text.txt';
    const areaFile = '201904.txt';
    const rl = readline.createInterface({
        input: fs.createReadStream(areaFile),
        // crlfDelay: Infinity
        // historySize: 2,
        terminal: true,
    });
    let lineCount = 0;
    let keys;
    const result = [];

    const provinceObj = {};
    const areaObj = {};
    const cityObj = {};

    const codeRecord = {};

    rl.on('line', (line) => {
    	const list = line.match(/(\S+)/g);
    	if (lineCount === 0) {
    		keys = list;
    		// keys
    		// 序号	省代码	省名称	地级市代码	地级市名称	区县代码	区县名称	乡镇代码	乡镇名称
	    } else {
    		const obj = {};
    		list.forEach((value, index) => {
    			const k = keys[index];
    			obj[k] = value;
		    });
		    // result.push(obj);
		    const provinceCode =  obj['省代码'].substring(0,2);
		    const provinceName = obj['省名称'];
		    const cityCode = obj['地级市代码'].substring(0,4);
		    const cityName = obj['地级市名称'];
		    const areaCode = obj['区县代码'];
		    const areaName = obj['区县名称'];

		    let provinceItem = provinceObj[provinceCode];
		    let cityItem = cityObj[cityCode];
		    let areaItem = areaObj[areaCode];

		    if (areaItem) {
			    return;
		    }
		    areaItem = { name: areaName };
		    areaObj[areaCode] = areaItem;



		    const cityArea = { areaId: areaCode };
		    if (cityItem) {
		    	// console.log('has city item ', cityCode, ', record code ? ', codeRecord[areaCode]);
		    	if (!codeRecord[areaCode]) {
				    cityItem.areas.push(cityArea);
				    codeRecord[areaCode] = true;
 			    }
		    } else {
		    	cityItem = { name: cityName, areas: [cityArea] };
		    	cityObj[cityCode] = cityItem;
		    	codeRecord[areaCode] = true;
			    // console.log('has not city item ', cityCode, ', record code ? ', codeRecord[areaCode]);
		    }

		    const provinceCity = { cityId: cityCode };
		    if (provinceItem) {
		    	if (!codeRecord[cityCode]) {
				    provinceItem.cities.push(provinceCity);
				    codeRecord[cityCode] = true;
			    }
		    } else {
			    provinceItem = { name: provinceName, cities: [provinceCity]};
			    provinceObj[provinceCode] = provinceItem;
			    codeRecord[cityCode] = true;
		    }
	    }
        lineCount += 1;
        // console.log(`Line from file: ${line}`);
        // if (lineCount > 80) {
        //     rl.close();
        // }
    });

    rl.on('close', (res) => {
    	console.log('close ', res);
    	console.log('handle line count = ', lineCount);
    	console.log('write province json');
    	fs.writeFileSync('province.json', JSON.stringify(provinceObj));

	    console.log('write city json');
    	fs.writeFileSync('city.json', JSON.stringify(cityObj));

	    console.log('write area json');
    	fs.writeFileSync('area.json', JSON.stringify(areaObj));
    });
};

readAreas();
